const express = require('express')
const mailer = require('../utils/mailer')
const codeModel = require('../Model/codeMail')
const mailModel = require('../Model/mailModel')
const router = express.Router()
//发送验证码
router.post('/regCode', async (req, res, next) => {
    const { mail } = req.body
    const isMail = await mailModel.findOne({ mail })
    const data = await codeModel.findOne({ mail })
    if (data) return res.json({ code: '304', msg: '请勿多次操作' })
    if (isMail) return res.json({ code: '304', msg: '该账户已注册' })
    const code = Math.floor(100000 + Math.random() * 900000);
    let expiresAt = new Date(Date.now() + 5 * 60 * 1000); // 当前时间 + 5分钟
    const mailOptions = {
        from: 'cbb88cai@163.com',
        to: mail,
        subject: `欢迎您${mail}：`,
        text: '您的验证码为：' + code + '(5分钟内过期)'
    }
    mailer.sendMail(mailOptions, async (err, info) => {
        if (err) return res.json({ code: '304', msg: '邮箱错误' })
        if (info) {
            await codeModel.create({ mail, code, expiresAt, createdAt: new Date() })
            res.json({ code: '200', msg: '发送成功' })
        }
    })
})

//注册账号
router.post('/reg', async (req, res, next) => {
    const { mail, code, password } = req.body
    const isMail = await mailModel.findOne({ mail })
    if (isMail) return res.json({ code: '304', msg: '该邮箱已注册' })
    const data = await codeModel.findOne({ code, mail })
    if (!data) {
        res.json({ code: '304', msg: '创建失败,验证码或邮箱错误' })
    } else {
        await mailModel.create({ mail, password,state:'正常',frequency:1 })
        await codeModel.deleteOne({ mail, code })
        res.json({ code: '200', msg: '创建成功' })
    }
})


module.exports = router